package cas;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 解决ABA问题
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/20 下午 12:37
 */
public class ABADemo {


    public static void main(String[] args) {
        AtomicStampedReference<User> atomicStampedReference = new AtomicStampedReference<>(new User("zhangsan", 15), 1);


        new Thread(() -> {
            //t1先修庙，等t2先将版本号和预期值读取
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            User exUser = atomicStampedReference.getReference();
            int exStamp = atomicStampedReference.getStamp();
            User u1 = new User("lisi", 17);
            //模拟ABA操作
            System.out.println("[t1]:"+ exUser + "\t版本：" + exStamp);
            atomicStampedReference.compareAndSet(exUser, u1, exStamp, exStamp + 1);
            u1=exUser;
            exUser = atomicStampedReference.getReference();
            exStamp = atomicStampedReference.getStamp();
            System.out.println("[t1]:"+exUser + "\t版本：" + exStamp);
            atomicStampedReference.compareAndSet(exUser, u1, exStamp, exStamp + 1);
            exUser = atomicStampedReference.getReference();
            exStamp = atomicStampedReference.getStamp();
            System.out.println("[t1]:"+exUser + "\t版本：" + exStamp);
        }, "t1").start();

        new Thread(() -> {
            int exStamp = atomicStampedReference.getStamp();
            User exUser = atomicStampedReference.getReference();
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = atomicStampedReference.compareAndSet(exUser, new User("wangwu", 22), exStamp, exStamp + 1);
            System.out.println("[t2]:"+b + "\t" + atomicStampedReference.getReference() + "\t版本：" + atomicStampedReference.getStamp());
        }, "t2").start();

    }

    @Data
    @AllArgsConstructor
    static class User {
        String name;
        Integer age;
    }
}
